package com.primaryedu.ui.app.leave;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.baidu.platform.comapi.map.C;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.dialog.CustomDialog;
import com.primaryedu.photo.PhotoPreviewIntent;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.utils.Logger;
import com.primaryedu.utils.Utils;
import com.primaryedu.widget.MyGridView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请假审批
 *
 * @author jun.wang
 * @description
 * @data 2018年1月5日
 */
public class LeaveApproveActivtiy extends BaseActivity implements OnClickListener {

    private TextView tv_leavetype_approve;
    private TextView tv_leavereanson;
    private RadioGroup radioGroup;
    private int opinionStatus = 1;
    private EditText edit_approveopinion;
    private String approveId;
    private CustomDialog.Builder ibuilder;
    private Button bt_submit_approve;
    private RadioButton rb_agree_approve;
    private RadioButton rb_disagree_approve;
    private TextView tv_leaveendtime;
    private TextView tv_leavenbegintime;
    private ImageView iv_pic1;
    private ImageView iv_pic2;
    private ImageView iv_pic3;
    private ArrayList<String> imagePaths = new ArrayList<>();
    private MyGridView gridView;
    private GridLeaveApproveAdapter gridAdapter;
    private static final int REQUEST_PREVIEW_CODE = 20;
    private TextView tv_approve_auditorName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_leave_approve);

        init();
    }

    @SuppressLint("NewApi")
    private void init() {
        Intent intent = getIntent();
        //请假类型
        String leavetype = intent.getStringExtra("type");
        //请假开始时间
        String begintime = intent.getStringExtra("begintime");
        //请假结束时间
        String endtime = intent.getStringExtra("endtime");
        //请假原因
        String leavereason = intent.getStringExtra("reason");
        //请假图片（可以为空，最多三张）
        String pic1 = intent.getStringExtra("pic1");
        String pic2 = intent.getStringExtra("pic2");
        String pic3 = intent.getStringExtra("pic3");
        Log.i("yy", "init: pic1=====" + pic1);
        Log.i("yy", "init: pic2=====" + pic2);
        Log.i("yy", "init: pic3=====" + pic3);
        //审批原因
        String leaveremark = intent.getStringExtra("remark");
        //审批人
        String auditorname = intent.getStringExtra("auditorname");
        int leaveStaus = intent.getIntExtra("staus", 0);
        Log.i("yy", "init: leaveStaus=====" + leaveStaus);
        approveId = intent.getStringExtra("id");
        Log.i("yy", "init: approveId=====" + approveId);
        ((TextView) findViewById(R.id.title)).setText("请假审批");
        findViewById(R.id.back).setOnClickListener(this);


        //请假类型
        tv_leavetype_approve = (TextView) findViewById(R.id.tv_leavetype_approve);
        tv_leavetype_approve.setText(leavetype);
        //请假开始时间
        tv_leavenbegintime = (TextView) findViewById(R.id.tv_leavenbegintime);
        tv_leavenbegintime.setText(begintime);
        //请假结束时间
        tv_leaveendtime = (TextView) findViewById(R.id.tv_leaveendtime);
        tv_leaveendtime.setText(endtime);
        //请假原因
        tv_leavereanson = (TextView) findViewById(R.id.tv_leavereanson);
        tv_leavereanson.setText(leavereason);
        //请假图片
        if (!pic1.equals("")) {
            imagePaths.add(Contants.course_api + pic1);
        }
        if (!pic2.equals("")) {
            imagePaths.add(Contants.course_api + pic2);
        }
        if (!pic3.equals("")) {
            imagePaths.add(Contants.course_api + pic3);
        }
        gridView = (MyGridView) this.findViewById(R.id.gridView_leaveapprove);
        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 3 ? 3 : cols;
        gridView.setNumColumns(cols);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String imgs = (String) parent.getItemAtPosition(position);
//					Toast.makeText(DynamicPublishActivity.this, "1" + position, Toast.LENGTH_SHORT).show();
                PhotoPreviewIntent intent = new PhotoPreviewIntent(LeaveApproveActivtiy.this);
                intent.setCurrentItem(position);
                //如果不加这行会导致选完图片以后在主界面点击图片预览会多出一张没有default_error 的图片
//                    imagePaths.remove(imagePaths.size()-1);
                intent.setPhotoPaths(imagePaths);
                startActivityForResult(intent, REQUEST_PREVIEW_CODE);
            }
        });

        gridAdapter = new GridLeaveApproveAdapter(imagePaths);
        gridView.setAdapter(gridAdapter);

        //审批人
        tv_approve_auditorName = (TextView) findViewById(R.id.tv_approve_auditorName);
        tv_approve_auditorName.setText(GlobalData.getUsername(this));
        //审批意见
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        radioGroup.setOnCheckedChangeListener(new LeaveApproveActivtiy.OpinionRadioButtonListener());//给RadioGroup绑定监视器

        rb_agree_approve = (RadioButton) findViewById(R.id.rb_agree_approve);
        rb_disagree_approve = (RadioButton) findViewById(R.id.rb_disagree_approve);
        //意见内容
        edit_approveopinion = (EditText) findViewById(R.id.edit_approveopinion);
        //提交
        bt_submit_approve = (Button) findViewById(R.id.bt_submit_approve);
        findViewById(R.id.bt_submit_approve).setOnClickListener(this);

        ImageView image = (ImageView) findViewById(R.id.image);
        if (leaveStaus == 1) {//请假审批同意
            image.setBackground(this.getResources().getDrawable(R.drawable.image_agree));
            disableRadioGroup(radioGroup);
            rb_agree_approve.setChecked(true);
            edit_approveopinion.setText(leaveremark);
            //输入框不可点击输入内容
            edit_approveopinion.setFocusable(false);
            //提交按钮不可见
            bt_submit_approve.setVisibility(View.GONE);
        } else if (leaveStaus == 0) {//未处理
            image.setBackground(this.getResources().getDrawable(R.drawable.leave_no_deal));
        } else if (leaveStaus == 2) {//请假审批不同意
            image.setBackground(this.getResources().getDrawable(R.drawable.image_disagree));
            disableRadioGroup(radioGroup);
            rb_disagree_approve.setChecked(true);
            edit_approveopinion.setText(leaveremark);
            //输入框不可点击输入内容
            edit_approveopinion.setFocusable(false);
            //提交按钮不可见
            bt_submit_approve.setVisibility(View.GONE);
        }
    }

    @Override
    protected int BindLayout() {
        return R.layout.activity_leave_approve;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    public void disableRadioGroup(RadioGroup testRadioGroup) {
        for (int i = 0; i < testRadioGroup.getChildCount(); i++) {
            testRadioGroup.getChildAt(i).setEnabled(false);
        }
    }

    class OpinionRadioButtonListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // 选中状态改变时被触发
            switch (checkedId) {
                case R.id.rb_agree_approve:
                    // 当用户选择同意时
                    opinionStatus = 1;
//					showToast("opinionStatus=1");
                    break;
                case R.id.rb_disagree_approve:
                    // 当用户选择不同意时
                    opinionStatus = 2;
//					showToast("opinionStatus=2");
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.bt_submit_approve:
                if (Utils.isBlank(edit_approveopinion.getText().toString())) {
                    showhintDialog("提示", "请输入您的审批意见！");
                } else {
                    showApplyleavetrue();
                }
                break;
            default:
                break;
        }

    }

    private void requestLeaveApprovelist() {
        showLoading("提交中...");
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.leaveApprove,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("response=leavelist=" + response);

                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                showToast("审批成功");
                                Intent intent = getIntent();
                                setResult(3, intent);
                                finish();
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");

//								leaveLists  = new Gson().fromJson(listStr,
//										new TypeToken<List<LeavelistBean.DataBean.ListBean>>() {
//										}.getType());
//								if (uploadMore) {
//									loadmoreList.addAll(leaveLists);
//									handler.sendEmptyMessage(1002) ;
//									uploadMore = false;
//								}else {
//									leavetempList.addAll(leaveLists);
//									handler.sendEmptyMessage(1001) ;
//								}

                                System.out.println("leaveLists==" + listStr);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("提交失败，请重新提交");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("id", approveId);
                map.put("status", String.valueOf(opinionStatus));
                map.put("remark", edit_approveopinion.getText().toString());
                map.put("auditorId", GlobalData.getUserId(getApplicationContext()));
                map.put("auditorName", GlobalData.getUsername(getApplicationContext()));
                Log.i("yy", "getName=======" + GlobalData.getUsername(getApplicationContext()));
                Log.i("yy", "getUserId======" + GlobalData.getUserId(getApplicationContext()));
                return map;

            }
        };
        requestQueue.add(stringRequest);
    }

    private void showApplyleavetrue() {
        ibuilder = new CustomDialog.Builder(LeaveApproveActivtiy.this);
        ibuilder.setTitle("请假");
        ibuilder.setMessage("确定审批吗？");
        ibuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });

        ibuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                requestLeaveApprovelist();
            }
        });

        Dialog dialog = ibuilder.create();
        dialog.show();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
        android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
        p.width = (int) (d.getWidth() * 0.8);    //宽度设置为屏幕的0.9
        dialog.getWindow().setAttributes(p);     //设置生效
    }

    public class GridLeaveApproveAdapter extends BaseAdapter {

        private ArrayList<String> listUrls;
        private LayoutInflater inflater;

        public GridLeaveApproveAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
            if (listUrls.size() == 7) {
                listUrls.remove(listUrls.size() - 1);
            }
            inflater = LayoutInflater.from(LeaveApproveActivtiy.this);
        }

        public int getCount() {
            return listUrls.size();
        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.include_item_published_grida, parent, false);
                holder.image = (ImageView) convertView.findViewById(R.id.item_grida_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            final String path = listUrls.get(position);
            Logger.withTag("yy").log("listurls=======" + listUrls.toString());
            Glide.with(LeaveApproveActivtiy.this)
//						.load(Contants.course_api + path)
                    .load(path)
                    .placeholder(R.drawable.default_error)
                    .error(R.drawable.default_error)
                    .centerCrop()
                    .crossFade()
                    .into(holder.image);
            return convertView;
        }

        class ViewHolder {
            ImageView image;
        }

    }
}
